package com.oop.example.gui;

import javax.swing.JTextPane;

public class XmlTextPane extends JTextPane {

    private boolean autoFormat = false;
    private static final long serialVersionUID = 6270183148379328084L;

    public XmlTextPane() {
        this.setEditorKitForContentType("text/xml", new XmlEditorKit());
        this.setContentType("text/xml");
    }

    public boolean isAutoFormat() {
        return autoFormat;
    }

    public void setAutoFormat(boolean autoFormat) {
        this.autoFormat = autoFormat;
    }

    @Override
    public void setText(String text) {
        if (autoFormat) {
            super.setText(new XmlFormatter().format(text));
        } else {
            super.setText(text);
        }
    }

    @Override
    public String getText() {
        String xmlString = super.getText();
        xmlString = xmlString.replaceAll("\n", "");
        return xmlString;
    }

    public class XmlFormatter {

        public String format(String unformattedXml) {
            unformattedXml = unformattedXml.replaceAll(">", ">\n").replaceAll("<", "\n<");
            unformattedXml = unformattedXml.replaceAll("\n\n", "\n").replaceAll("\n \n", " ");
            String xmlString = unformattedXml;
            return xmlString;
        }
    }
}